package com.pai4j.ugc.controller;

import com.pai4j.common.bean.PAIResponseBean;
import com.pai4j.common.bean.PAIResponseBeanUtil;
import com.pai4j.common.enums.ResponseCodeEnum;
import com.pai4j.domain.vo.request.interaction.InteractionMessageQueryRequestVO;
import com.pai4j.domain.vo.request.interaction.MarkInteractionMessageReadRequestVO;
import com.pai4j.domain.vo.request.interaction.SystemMessageSendRequestVO;
import com.pai4j.domain.vo.response.interaction.InteractionMessagePageResponseVO;
import com.pai4j.domain.vo.response.interaction.InteractionMessageResponseVO;
import com.pai4j.domain.vo.response.interaction.InteractionMessageStatisticsVO;
import com.pai4j.domain.vo.response.interaction.SystemMessageSendResponseVO;
import com.pai4j.remote.ugc.InteractionMessageClient;
import com.pai4j.ugc.service.InteractionMessageService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RestController;

/**
 * 互动消息控制器
 * 实现互动消息的REST API接口
 * 
 * 核心设计原则：
 * 1. 查询互动消息列表时，不会自动标记为已读（浏览不计为已读）
 * 2. 用户需要主动调用标记已读接口（例如点击查看详情时）
 * 3. 支持灵活的查询条件：全部/未读、按类型、按时间等
 * 4. 提供完整的统计信息，便于前端展示红点和数字角标
 * 
 * @author PAI4J Team
 */
@Slf4j
@RestController
public class InteractionMessageController implements InteractionMessageClient {
    
    @Autowired
    private InteractionMessageService interactionMessageService;
    
    /**
     * 分页查询互动消息列表
     * 
     * @param request 查询请求
     * @return 分页结果
     */
    @Override
    public PAIResponseBean<InteractionMessagePageResponseVO> pageMessages(InteractionMessageQueryRequestVO request) {
        log.info("【互动消息】分页查询，receiver: {}, type: {}, unreadOnly: {}", 
                request.getReceiver(), request.getType(), request.getUnreadOnly());
        
        try {
            InteractionMessagePageResponseVO response = interactionMessageService.pageInteractionMessages(request);
            return PAIResponseBeanUtil.success(response);
        } catch (Exception e) {
            log.error("【互动消息】分页查询失败，receiver: {}", request.getReceiver(), e);
            return PAIResponseBeanUtil.error(ResponseCodeEnum.ERROR.getCode(),"查询互动消息失败");
        }
    }
    
    /**
     * 查询未读互动消息数量
     * 
     * @param receiver 接收者账号
     * @return 未读消息数量
     */
    @Override
    public PAIResponseBean<Long> getUnreadCount(String receiver) {
        log.debug("【互动消息】查询未读数量，receiver: {}", receiver);
        
        try {
            long count = interactionMessageService.getUnreadCount(receiver);
            return PAIResponseBeanUtil.success(count);
        } catch (Exception e) {
            log.error("【互动消息】查询未读数量失败，receiver: {}", receiver, e);
            return PAIResponseBeanUtil.success(0L);
        }
    }
    
    /**
     * 查询指定类型的未读互动消息数量
     * 
     * @param receiver 接收者账号
     * @param type 消息类型
     * @return 未读消息数量
     */
    @Override
    public PAIResponseBean<Long> getUnreadCountByType(String receiver, Integer type) {
        log.debug("【互动消息】查询指定类型未读数量，receiver: {}, type: {}", receiver, type);
        
        try {
            long count = interactionMessageService.getUnreadCountByType(receiver, type);
            return PAIResponseBeanUtil.success(count);
        } catch (Exception e) {
            log.error("【互动消息】查询指定类型未读数量失败，receiver: {}, type: {}", receiver, type, e);
            return PAIResponseBeanUtil.success(0L);
        }
    }
    
    /**
     * 获取互动消息统计信息
     * 
     * @param receiver 接收者账号
     * @return 统计信息
     */
    @Override
    public PAIResponseBean<InteractionMessageStatisticsVO> getStatistics(String receiver) {
        log.info("【互动消息】获取统计信息，receiver: {}", receiver);
        
        try {
            InteractionMessageStatisticsVO statistics = interactionMessageService.getStatistics(receiver);
            return PAIResponseBeanUtil.success(statistics);
        } catch (Exception e) {
            log.error("【互动消息】获取统计信息失败，receiver: {}", receiver, e);
            return PAIResponseBeanUtil.error(ResponseCodeEnum.ERROR.getCode(),"获取统计信息失败");
        }
    }
    
    /**
     * 批量标记互动消息为已读
     * 
     * @param request 标记已读请求
     * @return 标记已读的消息数量
     */
    @Override
    public PAIResponseBean<Integer> markMessagesAsRead(MarkInteractionMessageReadRequestVO request) {
        log.info("【互动消息】标记已读，receiver: {}, markAll: {}, messageIds: {}", 
                request.getReceiver(), request.getMarkAll(), request.getMessageIds());
        
        try {
            int count = interactionMessageService.markMessagesAsRead(request);
            return PAIResponseBeanUtil.success(count);
        } catch (Exception e) {
            log.error("【互动消息】标记已读失败，receiver: {}", request.getReceiver(), e);
            return PAIResponseBeanUtil.error(ResponseCodeEnum.ERROR.getCode(),"标记已读失败");
        }
    }
    
    /**
     * 一键全部已读
     * 标记指定用户的所有未读互动消息为已读
     * 
     * @param receiver 接收者账号
     * @param messageType 消息类型（可选，不传则标记所有类型）
     * @return 标记已读的消息数量
     */
    @Override
    public PAIResponseBean<Integer> markAllAsRead(String receiver, Integer messageType) {
        log.info("【互动消息】一键全部已读，receiver: {}, messageType: {}", receiver, messageType);
        
        try {
            int count = interactionMessageService.markAllAsRead(receiver, messageType);
            return PAIResponseBeanUtil.success(count);
        } catch (Exception e) {
            log.error("【互动消息】一键全部已读失败，receiver: {}, messageType: {}", receiver, messageType, e);
            return PAIResponseBeanUtil.error(ResponseCodeEnum.ERROR.getCode(),"一键全部已读失败");
        }
    }
    
    /**
     * 查询互动消息详情
     * 
     * @param messageId 消息ID
     * @return 消息详情
     */
    @Override
    public PAIResponseBean<InteractionMessageResponseVO> getMessageDetail(Long messageId) {
        log.debug("【互动消息】查询详情，messageId: {}", messageId);
        
        try {
            InteractionMessageResponseVO detail = interactionMessageService.getMessageDetail(messageId);
            if (detail == null) {
                return PAIResponseBeanUtil.error(ResponseCodeEnum.ERROR.getCode(),"消息不存在");
            }
            return PAIResponseBeanUtil.success(detail);
        } catch (Exception e) {
            log.error("【互动消息】查询详情失败，messageId: {}", messageId, e);
            return PAIResponseBeanUtil.error(ResponseCodeEnum.ERROR.getCode(),"查询消息详情失败");
        }
    }
    
    /**
     * 发送系统消息
     * 系统消息是一种特殊的互动消息，用于平台公告、活动通知、系统维护通知等场景
     * 
     * @param request 系统消息发送请求
     * @return 发送结果
     */
    @Override
    public PAIResponseBean<SystemMessageSendResponseVO> sendSystemMessage(SystemMessageSendRequestVO request) {
        log.info("【系统消息】接收发送请求，标题: {}, 接收者类型: {}, 接收者数量: {}", 
                request.getTitle(), 
                request.getReceiverType(), 
                request.getReceivers() != null ? request.getReceivers().size() : 0);
        
        try {
            SystemMessageSendResponseVO response = interactionMessageService.sendSystemMessage(request);
            return PAIResponseBeanUtil.success(response);
        } catch (Exception e) {
            log.error("【系统消息】发送失败", e);
            
            SystemMessageSendResponseVO errorResponse = new SystemMessageSendResponseVO();
            errorResponse.setSuccessCount(0);
            errorResponse.setFailCount(0);
            errorResponse.setMessage("系统消息发送失败: " + e.getMessage());
            
            return PAIResponseBeanUtil.error(ResponseCodeEnum.ERROR.getCode(),"系统消息发送失败");
        }
    }
}
